package com.vaccine.service.impl;

import com.vaccine.entity.Vaccine;
import com.vaccine.mapper.VaccineMapper;
import com.vaccine.service.VaccineService;
import com.vaccine.vo.PageInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class VaccineServiceImpl implements VaccineService {
    @Autowired
    private VaccineMapper vaccineMapper;

    @Override
    public PageInfo getByPage(PageInfo pageInfo) {
        IPage<Vaccine> page=new Page<>(pageInfo.getPageNum(),pageInfo.getPageSize());
        boolean flag= StringUtils.hasLength(pageInfo.getQuery());
        QueryWrapper<Vaccine> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(flag, "name",pageInfo.getQuery());
        queryWrapper.eq("status","1");
        queryWrapper.gt("count",0);
        page=vaccineMapper.selectPage(page, queryWrapper);
        pageInfo.setTotal(page.getTotal());
        pageInfo.setRows(page.getRecords());
        return pageInfo;
    }

    @Override
    @Transactional
    public void insert(Vaccine vaccine) {
        try {
            vaccine.setStatus(1);
            vaccineMapper.insert(vaccine);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    @Transactional
    public void update(Vaccine vaccine) {
        try {
            vaccineMapper.updateById(vaccine);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    @Transactional
    public void delete(Integer id) {
        try {
            vaccineMapper.deleteById(id);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    @Transactional
    public void deleteBatch(List<Integer> ids) {
        vaccineMapper.deleteBatchIds(ids);
    }

    @Override
    public String[] vaccinePlace(Integer id) {
        Vaccine vaccine = vaccineMapper.selectById(id);
        return vaccine.getPlace().split(";");
    }

    @Override
    @Transactional
    public Integer reduceCount(Integer id) {
        Vaccine vaccine = vaccineMapper.selectById(id);
        Integer count = vaccine.getCount();
        if (count > 0) {
            vaccine.setCount(count - 1);
            vaccineMapper.updateById(vaccine);
            return vaccine.getCount();
        }else{
            throw new RuntimeException("当前疫苗库存不足");
        }
    }
}
